package cn.edu.sysu.service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.edu.sysu.dao.UserDao;
import cn.edu.sysu.dto.UserDto;
import cn.edu.sysu.util.Transaction;
import cn.edu.sysu.util.TransactionRead;
import cn.edu.sysu.util.TransactionWrite;

public class UserService {

	UserDao uDao = UserDao.INSTANCE;

	Transaction read = TransactionRead.INSTANCE;
	Transaction write = TransactionWrite.INSTANCE;

	public List<UserDto> getUserList() throws SQLException {
		List<UserDto> list = uDao.getAllUsers(read);
		return list;
	}

	public Map<Integer, UserDto> getUserMap() throws SQLException {

		Map<Integer, UserDto> userMap = new HashMap<Integer, UserDto>();
		List<UserDto> list = this.getUserList();
		for (int i = 0; i < list.size(); i++) {
			UserDto u = list.get(i);
			userMap.put(u.getUser_id(), u);
		}
		return userMap;
	}

	public UserDto getUserById(int user_id) throws SQLException {
		List<UserDto> list = this.getUserList();
		for (int i = 0; i < list.size(); i++) {
			UserDto u = list.get(i);
			if (u.getUser_id() == user_id) {
				return u;
			}
		}
		return null;

	}

	public List<UserDto> getMailingList() throws SQLException {

		return uDao.getMailingUsers(read);
	}

	public UserDto getUserByEmail(String email) throws SQLException {

		this.getUserList();
		List<UserDto> list = this.getUserList();
		for (int i = 0; i < list.size(); i++) {
			UserDto u = list.get(i);
			if (u.getEmail().equals(email)) {
				return u;
			}
		}

		return null;
	}

	public List<UserDto> getRank(int problem_id) throws SQLException {
		return uDao.getRank(read, problem_id);
	}

	public boolean createUser(String email) {
		try {
			if(this.getUserByEmail(email) == null){
				uDao.insertUser(write, email);
				return true;
			}
			return false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}
}
